// pages/musics/Music.ts
// 初始化音频播放器
const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: false
});
// 是否正在播放
var isPlaying: boolean = false;
// 是否正在缓冲
var isBuffering: boolean = false;
// 音乐列表
let musicList: string[] = [];
// 当前音乐下标
var musicIndex = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    songLikeIcon: "../images/icon_collect_normal.png",
    songLoopIcon: "../images/icon_loop_normal.png",
    playMusicIcon: "../images/icon_music_play.png",
    musicProgress: 0,
    songTitle: "化风行万里",
    singer: "云朵",
    musicPlayTime: "00:00",
    musicTotalTime: "00:00",
    progress: 0.0, // 初始进度值
    countdown: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    musicList.push("http://ez.sycdn.kuwo.cn/41e6ab4bec18b96c707b98817e6d7e6a/6543683d/resource/n1/24/45/1086444718.mp3?bitrate$128&format$mp3&type$convert_url2")
    musicList.push("http://lj.sycdn.kuwo.cn/640f0ac5f426437fdb273fc2881fffc3/65448ef6/resource/n3/6/44/3638605905.mp3?bitrate$128&format$mp3&type$convert_url2")
    musicList.push("http://lv.sycdn.kuwo.cn/aaaf517433675857adb0d78625356cc1/65448f1d/resource/30106/trackmedia/M500003GlRon3pqcn8.mp3?bitrate$128&format$mp3&type$convert_url2")
    musicList.push("http://lv.sycdn.kuwo.cn/2e439be30c2bdef0a6d524d44aa955c4/65448f35/resource/30106/trackmedia/M500000lVhFQ38zrOD.mp3?bitrate$128&format$mp3&type$convert_url2")
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    innerAudioContext.destroy()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 喜欢
   */
  songLike() {
    this.setData({
      songLikeIcon: "../images/icon_collect_select.png",
    })
  },

  /**
   * 单曲循环
   */
  songLoop() {
    const isLoop = innerAudioContext.loop
    innerAudioContext.loop = !isLoop
    this.setData({
      songLoopIcon:isLoop? "../images/icon_loop_select.png":"../images/icon_loop_normal.png",
    })
  },


  /**
   * 上一首
   */
  playMusicLast() {
    musicIndex--;
    if (musicIndex < 0) {
      musicIndex = 0;
      wx.showToast({
        title: "已是第一首!",
        icon: "error",
        duration: 1000
      })
    } else {
      this.playMusic()
    }
  },

  /**
   * 下一首
   */
  playMusicNext() {
    musicIndex++;
    if (musicIndex >= musicList.length) {
      musicIndex = musicList.length - 1;
      wx.showToast({
        title: "已是最后一首!",
        icon: "error",
        duration: 1000
      })
    } else {
      this.playMusic()
    }
  },

  /**
   * 播放音乐
   */
  playMusic() {
    innerAudioContext.src = musicList[musicIndex]
    if (isPlaying) {
      innerAudioContext.pause()
    } else {
      if (isBuffering) {
        innerAudioContext.play()
      }
    }

    innerAudioContext.onCanplay(() => {
      console.log('音频缓冲完成')
      isBuffering = true
      innerAudioContext.play()
    })

    innerAudioContext.onTimeUpdate(() => {
      const currentTime = innerAudioContext.currentTime
      const totalTime = innerAudioContext.duration
      // console.log('音频播放的当前时间：', currentTime + " - " + (currentTime / totalTime) * 100)

      this.setData({
        musicProgress: Math.round((currentTime / totalTime) * 100),
        musicPlayTime: this.formatMusicTime(Math.round(currentTime)),
        musicTotalTime: this.formatMusicTime(Math.round(totalTime))
      })
    })

    innerAudioContext.onPlay(() => {
      console.log('音频播放')
      isPlaying = true,
        this.setData({
          playMusicIcon: "../images/icon_music_pause.png",
        })
    })

    innerAudioContext.onPause(() => {
      console.log('音频暂停')
      isPlaying = false,
        this.setData({
          playMusicIcon: "../images/icon_music_play.png"
        })
    })

    innerAudioContext.onEnded(() => {
      console.log('音频结束')
      this.setData({
        musicPlayTime: "00:00",
        musicProgress: 0,
      })
    })

    innerAudioContext.onError((error) => {
      console.log('音频错误' + error)
    })
  },

  // 格式化音乐时长 00:00
  formatMusicTime: function (formatTime: number) {
    const minutes = Math.floor(formatTime / 60);
    const remainingSeconds = formatTime % 60;
    const minutesRemaining = minutes % 60;
    const minutesString = minutesRemaining < 10 ? '0' + minutesRemaining : minutesRemaining;
    const secondsString = remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds;
    return `${minutesString}:${secondsString}`;
  },

  // 格式化音乐时长 00:00
  formatVodeoTime: function (formatTime: number) {
    const minutes = Math.floor(formatTime / 60);
    const remainingSeconds = formatTime % 60;
    const hours = Math.floor(minutes / 60);
    const minutesRemaining = minutes % 60;
    const hoursString = hours < 10 ? '0' + hours : hours;
    const minutesString = minutesRemaining < 10 ? '0' + minutesRemaining : minutesRemaining;
    const secondsString = remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds;
    return `${hoursString}:${minutesString}:${secondsString}`;
  }

})